package Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/4/6
 * \* Time: 16:20
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class Demo10 {
    public static void main(String[] args) {
        //通过callable来描述一个任务
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i <= 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        //为了让线程执行callable中的任务，需要一个辅助类
        FutureTask<Integer> task = new FutureTask<>(callable);
        //创建线程，来完成这里的计算工作
        Thread t = new Thread(task);
        t.start();

        // 如果线程的任务没有执行完呢, get 就会阻塞.
        // 一直阻塞到, 任务完成了, 结果算出来了
        try {
            System.out.println(task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
